package com.media.entrance.websocket;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnMessage;
import java.net.URI;
import java.net.URISyntaxException;

@Slf4j
@ClientEndpoint
// just for test
public class WebSocketCustomerClient extends WebSocketClient {

    public WebSocketCustomerClient(URI serverUri) {
        super(serverUri);
    }

    private MessageListener messageListener;

    public void setMessageListener(MessageListener listener) {
        this.messageListener = listener;
    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        // TODO Auto-generated method stub
        log.info("------ MyWebSocket onOpen ------");
        if (messageListener != null) {
            messageListener.onMessage("client session open!");
        }
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        // TODO Auto-generated method stub
        log.info("------ MyWebSocket onClose ------{}",arg1);
        if (messageListener != null) {
            messageListener.onMessage("client session close!");
        }
    }

    @Override
    public void onError(Exception arg0) {
        // TODO Auto-generated method stub
        log.error("------ MyWebSocket onError ------{}" + arg0  + "--------");
    }

    @Override
    @OnMessage
    public void onMessage(String arg0) {
        // TODO Auto-generated method stub
        log.info("-------- 接收到服务端数据： " + arg0 + "--------");
        if (messageListener != null) {
            messageListener.onMessage(arg0);
        }
    }

    interface MessageListener {
        void onMessage(String message);
    }
}

